package com.five.wisdomEat.until;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

public class QRCodeUtil {
    //编码格式，采用utf-8
    private static final String UNICODE = "utf-8";
    //图片格式
    private static final String FORMAT = "JPG";
    //二维码宽度像素pixels数量
    public static final int QRCODE_WIDTH = 300;
    //二维码高度像素pixels数量
    public static final int QRCODE_HEIGHT = 300;
    //LOGO宽度像素pixels数量
    public static final int LOGO_WIDTH = 100;
    //LOGO宽度像素pixels数量
    public static final int LOGO_HEIGHT = 100;

    //生成二维码图片
    //content 二维码内容
    //logoPath logo图片地址
    public static BufferedImage createImage(String content) throws WriterException {
        //用于设置QR二维码参数
        Hashtable<EncodeHintType,Object> hints = new Hashtable<EncodeHintType,Object>();
        //设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
        //设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET,UNICODE);
        //MARGIN为1
        hints.put(EncodeHintType.MARGIN,1);
        //生成BitMatrix二维码，参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        //图片生成
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //开始利用二维码数据创建Bitmap图片，分别设置为黑<0xFFFFFFFF> 白<0xFF000000>两色
        for(int x = 0; x<width; x++){
            for (int y = 0; y<height; y++){
                image.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
            }
        }
//        if(logoPath == null || "".equals(logoPath)){
//            return image;
//        }
        //插入图片
//        QRCodeUtil.insertImage(image,logoPath);
        return image;
    }

    //生成二维码图片，直接输出到OutputStream
    public static  void encode(String content,String logoPath, OutputStream output) throws WriterException, IOException {
        BufferedImage image = QRCodeUtil.createImage(content);
        ImageIO.write(image,FORMAT,output);
    }
}
